package com.detrum.sportcamera.nfstask;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.detrum.NFSVideo;
import com.detrum.base.BaseStatic;
import com.detrum.bean.FileBean;
import com.detrum.sportcamera.finals.SportStatic;
import com.detrum.sportcamera.nfsnet.NfsRequestManager;
import com.detrum.sqlite.SqliteMediaOperation;
import com.detrum.utils.LogUtils;
import com.detrum.utils.NfsUtil;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

/**
 * Created by abc on 2018/1/9.
 */

public class NfsDownLoadTask extends AsyncTask<FileBean, String, Void> {
    private final String TAG = "NfsDownLoadTask";
    private Context context;
    private NfsDownLoadCall nfsDownLoadCall;
    private boolean isStop,isDelete;
    private long currentSize = 0;
    private int sendCountSize;
    private int sendSize;
    private long countSize = 0;
    private int index;

    public interface NfsDownLoadCall {
        void finish();

        void itemStart(String fileName,String num);

        void itemFinish(String fileName,String num,int currentSize);

        void itemFail(String fileName);

        void countSize(int countSize);

        void itemVideoSize(String fileName,String num, int videoSize);
    }

    public NfsDownLoadTask(Context context, int index, NfsDownLoadCall nfsDownLoadCall) {
        this.context = context;
        this.index = index;
        this.nfsDownLoadCall = nfsDownLoadCall;
        isDelete = false;
    }

    public void Stop() {
        isStop = true;
        SportStatic.isDownloading = false;
    }

    public void Delete(){
        isDelete = true;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        SportStatic.isDownloading = false;
        nfsDownLoadCall.finish();
    }

    @Override
    protected void onProgressUpdate(String... fileNames) {
        super.onProgressUpdate(fileNames);
        if (fileNames[0].endsWith("start")) {
            String[]str=fileNames[0].split("----");
            nfsDownLoadCall.itemStart(str[0],str[1]);
        } else if (fileNames[0].endsWith("complete")) {
            String[] strs = fileNames[0].split("----");
            nfsDownLoadCall.itemFinish(strs[0],strs[1],sendSize);
        } else if (fileNames[0].endsWith("fail")) {
            nfsDownLoadCall.itemFail(fileNames[0].split("----")[0]);
        } else if (fileNames[0].startsWith("countSize")) {
            nfsDownLoadCall.countSize(Integer.parseInt(fileNames[0].split("----")[1]));
        } else if (fileNames[0].endsWith("videoSize")) {
            String[]str1=fileNames[0].split("----");
            nfsDownLoadCall.itemVideoSize(str1[0],str1[1], sendSize);
        }
    }

    @Override
    protected Void doInBackground(FileBean... fileBeans) {
        SportStatic.isDownloading = true;
        for (int i = 0; i < fileBeans.length; i++) {
            if (fileBeans[i].isSelect()) {
                countSize += fileBeans[i].getSize();
                Log.e(TAG, "countSize = " + countSize);
            }
        }
        currentSize = 0;
        if (countSize > Integer.MAX_VALUE) {
            sendCountSize = 1000000000;
        } else {
            sendCountSize = (int) countSize;
        }
        publishProgress("countSize----" + sendCountSize);
        LogUtils.e(TAG + " fileBeans.length = " + fileBeans.length);
        for (int i = 0; i < fileBeans.length; i++) {
            if (isStop) {
                LogUtils.e(TAG + " isStop = " + isStop);
                break;
            }
            final String fileName = fileBeans[i].getFileName();
            if (NfsUtil.isImageFile(fileName)) {
                SqliteMediaOperation.getInstence(context).UpdataItemLocal(1, fileName);
                long jpgSize = fileBeans[i].getSize();
                currentSize += jpgSize;
                if (countSize > Integer.MAX_VALUE) {
                    sendSize = (int) (currentSize * sendCountSize / countSize);
                } else {
                    sendSize = (int) currentSize;
                }
                publishProgress(fileName + "----"+(i+1)+"/"+fileBeans.length+"----complete");
            } else if (NfsUtil.isVideoFile(fileName)) {
                String cacheName = SqliteMediaOperation.getInstence(context).getFilePath(fileName);
                if (cacheName != null && !cacheName.endsWith(".jpg")) {//已经下载完成的
                    SqliteMediaOperation.getInstence(context).UpdataItemLocal(1, fileName);
                    long jpgSize = fileBeans[i].getSize();
                    currentSize += jpgSize;
                    if (countSize > Integer.MAX_VALUE) {
                        sendSize = (int) (currentSize * sendCountSize / countSize);
                    } else {
                        sendSize = (int) currentSize;
                    }
                    publishProgress(fileName +"----"+(i+1)+"/"+fileBeans.length+ "----complete");
                } else {
                    publishProgress(fileName +"----"+(i+1)+"/"+fileBeans.length+ "----start");
                    downLoadFile(fileBeans[i],(i+1)+"/"+fileBeans.length, index);
                }
            }
        }
        return null;
    }

    private void downLoadFile(FileBean fileBean,String num, int downLoadIndex) {
        int downloadFlag = NFSVideo.open(fileBean.getNfsPath(), 0, downLoadIndex);
        Log.i(TAG, "downloadFlag: " + downloadFlag);
        if (downloadFlag < 0) {
            NFSVideo.close(downLoadIndex);
            nfsDownLoadCall.itemFail(fileBean.getFileName());
        }
        File downloadFile = new File(BaseStatic.MediaPath);
        if (!downloadFile.exists()) {
            downloadFile.mkdirs();
        }
        long oldSize = 0;
        File outputFile = new File(downloadFile, NfsUtil.splitName(fileBean.getNfsPath()) + ".det");
        if (outputFile.length() != 0) {
            oldSize = outputFile.length();
            NFSVideo.lseek(oldSize, 0, downLoadIndex);
            currentSize += oldSize;
            if (countSize > Integer.MAX_VALUE) {
                sendSize = (int) (currentSize * sendCountSize / countSize);
            } else {
                sendSize = (int) currentSize;
            }
            publishProgress(fileBean.getFileName() +"----"+num+ "----videoSize");
        }
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(outputFile, true));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        byte[] data;
        int sizeTime = (int) (fileBean.getSize() / (1024 * 10) + 1);
        for (int i = 0; i < sizeTime; i++) {
            if (isStop) {
                if(isDelete){
                    outputFile.delete();
                }
                LogUtils.i(TAG + "downloadVideo stop isDelete = "+isDelete);
                break;
            }
            data = new byte[1024 * 10];
            int length = NFSVideo.read(data, data.length, downLoadIndex);
            if (length > 0) {
                currentSize += length;
                try {
                    bos.write(data, 0, length);
                    data = null;
                    if (countSize > Integer.MAX_VALUE) {
                        sendSize = (int) (currentSize * sendCountSize / countSize);
                    } else {
                        sendSize = (int) currentSize;
                    }
                    if(i%(sizeTime/100)==0||i==sizeTime){
                        publishProgress(fileBean.getFileName() +"----"+num+ "----videoSize");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        LogUtils.i(TAG + " getSize === " + fileBean.getSize());
        if (outputFile.length() == fileBean.getSize()) {
            //下载完成或更新数据库，同时删除原有缩略图文件
            File outputFile2 = new File(downloadFile, NfsUtil.splitName(fileBean.getNfsPath()));
            outputFile.renameTo(outputFile2);
            String cachePath = SqliteMediaOperation.getInstence(context).getFilePath(fileBean.getFileName());
            LogUtils.i(TAG + " cachePath === " + cachePath);
            if (cachePath != null) {
                File file = new File(cachePath);
                if (file != null) {
                    file.delete();
                }
            }
            int videoUpdate = SqliteMediaOperation.getInstence(context).UpdataDownloadItem(outputFile2.getPath(), fileBean.getFileName());
            LogUtils.i(TAG + " videoUpdate === " + videoUpdate);
            publishProgress(fileBean.getFileName() +"----"+num+ "----complete");
        }
        LogUtils.i(TAG + " outputFile === " + outputFile.length());
        NFSVideo.close(downLoadIndex);
    }

    int time;
}
